package com.nxmu.hire.common.util;

import com.alibaba.fastjson.JSON;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Objects;

public class CookieUtil {

    /**
     * 取出cookie中的对象
     * @param clazz
     * @param cookies
     * @param cookieKey
     * @param <T>
     * @return
     */
    public static <T> T cookieToObject(Class<T> clazz, Cookie[] cookies,String cookieKey){
        if (Objects.isNull(cookies) || StringUtils.isEmpty(cookieKey)) return null;
        for (Cookie cookie : cookies) {
            if (Objects.equals(cookieKey,cookie.getName())) {
                String cookieValue = cookie.getValue();
                try {
                    URLDecoder.decode(cookieValue,"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                return JSON.parseObject(cookieValue, clazz);
            }
        }
        return null;
    }

    /**
     * 将对象存入cookie中
     * @param response
     * @param cookieKey
     * @param object
     */
    public static <T> void addObjectToCookie(HttpServletResponse response, String cookieKey, T object){
        String objectStr = null;
        try {
            objectStr = URLEncoder.encode(JSON.toJSONString(object),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Cookie cookie = new Cookie(cookieKey,objectStr);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

}
